/* jshint esversion: 11 */

export function makeDraggable(elem){
    let style=elem.style,relate;

    style.left = elem.offsetLeft + "px";
    style.top  = elem.offsetTop  + "px";
    let isDraging = false, timer=null;
    let getClient=(ev)=>[ev.clientX,ev.clientY];
    elem.addEventListener("mousedown",(event)=>{
        style.position="absolute";
        isDraging = true;
        let _t1=getClient(event);
        let _t2=[elem.offsetLeft,elem.offsetTop];
        relate=_t1.map((e,i)=>e - _t2[i]);
    });
    window.addEventListener("mousemove",(event)=>{
        if(!isDraging)return;

        let now=getClient(event);
        let fixed=now.map((e,i)=>e - relate[i]);
        style.left = fixed[0] + "px";
        style.top  = fixed[1] + "px";

        clearTimeout(timer);
        timer = setTimeout(()=>{
            isDraging = false;
        },3*1000);
    });
    window.addEventListener("mouseup",(event)=>{
        isDraging = false;
    });
}